<template>
  <div class="app-container">
    <basic-container>
      <el-form :inline="true" :model="searchForm" ref="searchForm">
        <el-form-item>
          <el-input v-model.trim="searchForm.roomName" placeholder="请输入教室名称" clearable class="st-input-w"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search()">搜 索</el-button>
          <el-button type="default" @click="resetSearch('searchForm')">重 置</el-button>
        </el-form-item>
      </el-form>
      <el-button
          class="add-btn"
          size="mini"
          type="primary"
          icon="el-icon-plus"
          @click="add"
          style="margin-bottom: 15px"
      >
        新增
      </el-button>
      <el-button
          class="add-btn"
          size="mini"
          type="danger"
          icon="el-icon-delete"
          @click="removeBtn"
          :disabled='chooseCheckBox'
          style="margin-bottom: 15px"
      >
        批量删除
      </el-button>
      <vxe-table
          border
          resizable
          highlight-hover-row
          show-overflow
          ref="xTable1"
          :data="tableData"
          @checkbox-all="selectAllEvent"
          @checkbox-change="selectChangeEvent">
        <vxe-table-column type="checkbox" width="60"></vxe-table-column>
        <vxe-table-column field="roomName" title="教室名称" min-width="100"></vxe-table-column>
        <vxe-table-column field="equipName" title="教室分类" min-width="60">
          <template v-slot:default="{ row }">
            <div v-for="(item,index) in typeList" :key="index">
              <span v-if="item.typeId === row.typeId">{{ item.typeName }}</span>
            </div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="pName" title="教室用途" min-width="80"></vxe-table-column>
        <vxe-table-column field="eqName" title="设备" min-width="100"></vxe-table-column>
        <vxe-table-column field="cost" title="能源费" min-width="60">
          <template v-slot:default="{ row }">
            <span>{{ row.cost }}.00</span>
          </template>
        </vxe-table-column>
        <vxe-table-column field="status" title="状态" min-width="60">
          <template v-slot:default="{ row }">
            <div v-if="row.status === 1" style="color: #42b983">可用</div>
            <div v-else style="color: red">不可用</div>
          </template>
        </vxe-table-column>
        <vxe-table-column field="remark" title="备注" min-width="150"></vxe-table-column>
        <vxe-table-column field="id" title="操作" width="150" fixed="right" align="center">
          <template v-slot:default="{ row }">
            <div style="display: inline-block">
              <el-button size="mini" @click="edit(row)" type="primary" icon="el-icon-edit" title="编辑"/>
              <el-button  type="danger" @click="del(row)" icon="el-icon-delete" size="mini" title="删除"/>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
      <vxe-pager
          :loading="loading"
          :current-page="tablePage.page"
          :page-size="tablePage.size"
          :total="tablePage.totalElements"
          background
          @page-change="handlePageChange"
      >
      </vxe-pager>
      <!--新增弹出窗 start-->
      <el-dialog :title="title" width="550px" :close-on-click-modal="false" :visible.sync="dialogFormVisible" :before-close="close">
        <el-form :model="model" :rules="rules" ref="ruleForm" label-width="120px">
          <el-form-item label="教室名称" prop="roomName">
            <el-input v-model="model.roomName" placeholder="请输入教室名称" style="width: 350px"></el-input>
          </el-form-item>
          <el-form-item label="教室分类" prop="typeId">
            <el-select v-model="model.typeId" placeholder="请选择教室分类" style="width: 350px">
              <el-option
                  v-for="item in typeList"
                  :key="item.typeId"
                  :label="item.typeName"
                  :value="item.typeId">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教室用途" prop="purposeId">
            <el-select v-model="model.purposeId" multiple placeholder="请选择教室用途" style="width: 350px">
              <el-option
                  v-for="item in purposeList"
                  :key="item.purposeId"
                  :label="item.purposeName"
                  :value="String(item.purposeId)">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教室设备" prop="equipId">
            <el-select v-model="model.equipId" multiple placeholder="请选择教室设备" style="width: 350px">
              <el-option
                  v-for="item in equipmenteList"
                  :key="item.equipId"
                  :label="item.equipName"
                  :value="String(item.equipId)">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="能源费" prop="cost">
            <el-input v-model.number="model.cost" placeholder="请输入教室能源费" style="width: 350px"></el-input>
          </el-form-item>
          <el-form-item label="教室缩略图" prop="urls">
            <!-- <upload
                :action="actionUrl"
                :avatar-type="avatar"
                :image-url="model.url"
                v-model="model.url"
                :limit="1"
                @input="avatarDetail">
            </upload> -->
             <upload-list
                v-model="model.urls"
                :action="actionUrl"
                @uploadMoreImg="avatarDetail"
            ></upload-list>
          </el-form-item>
          <el-form-item label="状态">
            <el-radio-group v-model="model.status">
              <el-radio :label="0">不可用</el-radio>
              <el-radio :label="1">可用</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" :rows="4" v-model="model.remark" placeholder="请输入备注信息" style="width: 350px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetForm('ruleForm')">取消</el-button>
            <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
      <!--新增弹出窗 end-->

    </basic-container>
  </div>
</template>

<script>
import { baseUrl } from '@/config/env';
import Upload from '@/components/jst-components/avatar-upload';
import UploadList from '@/components/jst-components/upload';
import api from "@/api/classroom/classroom";
import {mapGetters} from 'vuex';

export default {
  name: "room",
  components:{
    Upload,
    UploadList
  },
  data(){
    return{
      loading: false,
      dialogFormVisible: false,
      title: '教室新增',
      tableData: [],
      searchForm: {  //搜索表单
        roomName: '',
      },
      removeIds: [],
      avatar: 'avatar',
      actionUrl: baseUrl + 'api/users/updateAvatar',// 头像上传地址
      avatarUrl:{},
      tablePage: {
        total: 0,
        page: 1,
        size: 10,
        background: true,
        totalElements: 0
      },
      model: {
        roomName: '',
        typeId: '',
        purposeId: [],
        equipId: [],
        cost: null,
        urls: [],
        status: 1,
        remark: ''
      },
      rules: {
        roomName: [
          { required: true, message: '请输入教室名称', trigger: 'blur' },
        ],
        typeId: [
          { required: true, message: '请选择教室分类', trigger: 'change' }
        ],
        purposeId: [
          { required: true, message: '请选择教室用途', trigger: 'change' }
        ],
        equipId: [
          { required: true, message: '请选择教室设备', trigger: 'change' }
        ],
        cost: [
          { required: true, message: '请输入教室能源费用', trigger: 'blur' },
          { type: 'number', message: '能源费用必须为数字值'}
        ],
        urls: [
          { required: true, message: '请上传图片', trigger: 'blur' }
        ]
      },
      equipmenteList: [], // 设备
      purposeList: [], // 用途
      typeList: [], // 分类
    }
  },
  created() {
    this.init();
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    chooseCheckBox() {
      return this.removeIds.length ? false : true;
    },
  },
  methods:{
    async init() {
      await this.getEquipmente();
      await this.getPurpose();
      await this.getCompList();
      await this.getType();
    },
    getCompList() {
      const params = {
        roomName: this.searchForm.roomName,
        page: this.tablePage.page,
        size: this.tablePage.size,
      }
      return api.queryClassroomList(params, 'get').then((res) => {
        this.tableData = res.content;
        this.tablePage.totalElements = res.totalElements;
        this.tableData.forEach((item) => {
          item.pName = '';
          this.purposeList.forEach((itm) => {
            if (item.purposeId.indexOf(itm.purposeId) != -1) {
              item.pName += `${itm.purposeName},`;
            }
          });
          item.pName = item.pName.slice(0,item.pName.length-1);
          item.eqName = '';
          this.equipmenteList.forEach((itm) => {
            if (item.equipId.indexOf(itm.equipId) != -1) {
              item.eqName += `${itm.equipName},`;
            }
          });
          item.eqName = item.eqName.slice(0,item.eqName.length-1);
        });
      })
    },
    // 获取设备
    getEquipmente() {
      const params = {}
      return api.queryEquipmente(params, 'get').then((res) => {
        this.equipmenteList = res.content;
      })
    },
    // 获取用途
    getPurpose() {
      const params = {}
      return api.queryRoomPurpose(params, 'get').then((res) => {
        this.purposeList = res.content;
      })
    },
    // 获取分类
    getType() {
      const params = {}
      return api.queryRoomType(params, 'get').then((res) => {
        this.typeList = res.content;
      })
    },
    // 搜索
    search() {
      this.tablePage.page = 1
      this.getCompList();
    },
    resetSearch() {
      this.searchForm = {};
      this.getCompList();
    },
    // 头像上传
    avatarDetail(value) {
        // console.log(value, '456');
        this.model.urls = value;
        // this.$refs.ruleForm.validateField('urls');
    },
    selectAllEvent ({ checked, records }) {
      this.removeIds = records.map((item)=>{ return item.roomId });
    },
    // eslint-disable-next-line no-unused-vars
    selectChangeEvent ({ checked, records }) {
      this.removeIds = records.map((item)=>{ return item.roomId });
    },
    // 分页发生改变事件 totalElements
    handlePageChange({currentPage, pageSize}) {
      this.tablePage.page = currentPage;
      this.tablePage.size = pageSize;
      this.getCompList();
    },
    //关闭弹窗，重置表单
    close(){
      this.dialogFormVisible = false;
      this.$refs['ruleForm'].resetFields();
    },
    resetForm(formName) {
      this.dialogFormVisible = false;
      this.$refs[formName].resetFields();
    },
    // 新增
    add() {
      this.dialogFormVisible = true;
      this.title = '教室新增';
      // this.$refs['ruleForm'].resetFields();
    },
    edit(val) {
      this.dialogFormVisible = true;
      this.title = '教室编辑';
      this.$nextTick(() => {
        this.model = _.cloneDeep(val);
        this.model.purposeId = this.model.purposeId.split(',');
        this.model.equipId = this.model.equipId.split(',');
      })
    },
    // 保存新增
    submitForm(formName) {
      let message = this.title === '教室编辑' ? '保存成功' : '新增成功';
      let type = this.title === '教室编辑' ? 'put' : 'post';
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const parmas = _.cloneDeep(this.model);
          parmas.purposeId = parmas.purposeId.join();
          parmas.equipId = parmas.equipId.join();
          api.queryClassroomList(parmas, type).then(() => {
            this.$message({
              message,
              type: 'success'
            });
            this.dialogFormVisible = false;
            this.getCompList();
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    del(val) {
      let ids = [];
      ids.push(val.roomId);
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.queryClassroomList(ids, 'delete').then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getCompList();
        });
      }).catch(() => {
        console.log('已取消')
      });
    },
    // 批量删除
    removeBtn() {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        api.queryClassroomList(this.removeIds, 'delete').then(() => {
          this.$message({
            type: 'success',
            message: '删除成功。'
          });
          this.getCompList();
        })
      }).catch(() => {
        console.log('已取消')
      });
    },
  }
}
</script>

<style lang="scss" scoped>
// /deep/.el-upload-list__item.is-ready {
//   display: none;
// }
</style>